package com.example.demo.connectionpool;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 驱动连接池测试
 *
 * @author yunda
 * @date 2021/1/17 9:37
 */
@Slf4j
public class ConnectionPoolTest {

    static ConnectionPool pool = new ConnectionPool(10);
    // 保证所有ConnectionRunner能够同时开始
    static CountDownLatch start = new CountDownLatch(1);
    // main线程将会等待所有ConnectionRunner结束后才能继续执行
    static CountDownLatch end;

    public static void main(String[] args) throws Exception {
        // 线程数量，可以修改线程数量进行观察
        int threadCount = 100;
        // 每个子线程执行20次获取数据库连接操作
        int count = 20;
        long connectionTimeout = 0;
        end = new CountDownLatch(threadCount);
        AtomicInteger got = new AtomicInteger();
        AtomicInteger notGot = new AtomicInteger();
        for (int i = 0; i < threadCount; i++) {
            Thread thread = new Thread(new ConnetionRunner(count, connectionTimeout, got, notGot), "ConnectionRunnerThread");
            thread.start();
        }
        log.info("start");
        start.countDown();
        end.await();
        log.info("end");
        log.info("total invoke: " + (threadCount * count));
        log.info("got connection: " + got);
        log.info("not got connection " + notGot);
    }

    static class ConnetionRunner implements Runnable {
        int count;
        long connectionTimeout;
        AtomicInteger got;
        AtomicInteger notGot;

        public ConnetionRunner(int count, long connectionTimeout, AtomicInteger got, AtomicInteger notGot) {
            this.count = count;
            this.connectionTimeout = connectionTimeout;
            this.got = got;
            this.notGot = notGot;
        }

        @Override
        public void run() {
            try {
                start.await();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            while (count > 0) {
                try {
                    // 从线程池中获取连接，如果1000ms内无法获取到，将会返回null
                    // 分别统计连接获取的数量got和未获取到的数量notGot
                    Connection connection = pool.fetchConnection(connectionTimeout);
                    if (connection != null) {
                        try {
                            connection.createStatement();
                            connection.commit();
                        } finally {
                            pool.releaseConnection(connection);
                            got.incrementAndGet();
                        }
                    } else {
                        notGot.incrementAndGet();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    count--;
                }
            }
            end.countDown();
        }
    }
}
